import { Dropdown, Form, Input, Modal, notification } from 'antd';
import { FC } from 'react';

import { usePost } from '@/api';
import EditIcon from '@/assets/icons/edit.svg';
import MoreIcon from '@/assets/icons/more.svg';
import { colors } from '@/config/theme';

interface GroupMoreProps {
  groupName: string;
  groupDesc: string;
  group: number;
  refresh: () => void;
}

export const GroupMore: FC<GroupMoreProps> = memo((props) => {
  const [visible, setVisible] = useState(false);
  const [form] = Form.useForm();
  const { loading: confirmLoading, runAsync } = usePost('/group/{group}/rename', {}, { manual: true });

  const submit = () => {
    form.validateFields().then((values) => {
      runAsync({
        group: props.group,
        ...values
      }).then(() => {
        setVisible(false);
        notification.success({ message: '操作成功' });
        props.refresh();
      });
    });
  };

  useEffect(() => {
    visible && form?.setFieldsValue({ groupName: props.groupName, groupDesc: props.groupDesc });
  }, [props.groupName, props.groupDesc, props.group, visible, form]);

  return (
    <>
      <Modal
        title="重命名"
        destroyOnClose
        open={visible}
        onOk={submit}
        confirmLoading={confirmLoading}
        onCancel={() => setVisible(false)}>
        <Form form={form}>
          <Form.Item label="版本名称" name="groupName" rules={[{ required: true }]}>
            <Input maxLength={20} />
          </Form.Item>
          <Form.Item label="版本备注" name="groupDesc" rules={[{ required: true }]}>
            <Input.TextArea />
          </Form.Item>
        </Form>
      </Modal>
      <Dropdown
        arrow
        trigger={['hover']}
        menu={{
          items: [
            {
              onClick() {
                setVisible(true);
              },
              key: '1',
              label: '重命名',
              icon: <EditIcon width="18" height="18" />
            }
          ]
        }}>
        <div>
          <MoreIcon onClick={(e: MouseEvent) => e.stopPropagation()} width="18" height="18" fill={colors.primary[500]} />
        </div>
      </Dropdown>
    </>
  );
});
